package com.example.surfaceviewcamera;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
	
	private SurfaceHolder mHolder;
	private Camera mCamera;
	
	public CameraSurfaceView(Context context){//, Camera camera) {
		super(context);
		
		this.mHolder = this.getHolder();
		this.mHolder.addCallback(this);
		this.mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}
	
	public CameraSurfaceView(Context context, AttributeSet attr) {
        super(context, attr);

        mHolder = this.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
	
	public void setCamera(Camera camera){
		mCamera = camera;
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
		try{
			if(mCamera != null){
				mCamera.setPreviewDisplay(holder);
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		try {
			if(mCamera == null){
				return;
			}
			mCamera.setDisplayOrientation(90);
			mCamera.setPreviewDisplay(mHolder);

		} catch (IOException e) {
			Log.e("camera", e.getMessage());
		} catch(Exception e){
			Log.v("camera", e.getMessage());
		}
					
        mCamera.startPreview();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
		}
	}
}
